import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getServerAuthSession } from "@/auth";

export async function POST(req: Request) {
  const session = await getServerAuthSession();
  const userId = (session as any)?.user?.id as string | undefined;
  if (!userId) return NextResponse.json({ error: "未登录" }, { status: 401 });
  const { postId } = await req.json();
  if (!postId) return NextResponse.json({ error: "缺少postId" }, { status: 400 });
  const existed = await prisma.like.findUnique({ where: { userId_postId: { userId, postId } } });
  if (existed) {
    await prisma.like.delete({ where: { id: existed.id } });
    return NextResponse.json({ liked: false });
  } else {
    await prisma.like.create({ data: { userId, postId } });
    return NextResponse.json({ liked: true });
  }
}